﻿using System;
using System.Reflection;
using AutoTAU.Properties;
using Microsoft.Win32;

namespace AutoTAU
{
    internal static class AutostartManager
    {
        /// <summary>
        /// Autostart property
        /// </summary>
        public static bool Autostart
        {
            get { return Settings.Default.Autostart; }
            set
            {
                // Set value in configuration
                Settings.Default.Autostart = value;
                Settings.Default.Save();

                // Update the registry according to the new setting
                RegistryKey runkey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                if (value)
                {
                    // Set to autostart (or update path with the current location)
                    try
                    {
                        if (runkey != null)
                            runkey.SetValue(Assembly.GetExecutingAssembly().GetName().Name,
                                            Assembly.GetExecutingAssembly().Location);
                    }
                    catch (Exception)
                    {
                    }
                }
                else
                {
                    try
                    {
                        // Remove value from run key (if said value exists)
                        if (runkey != null) runkey.DeleteValue(Assembly.GetExecutingAssembly().GetName().Name);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }

        /// <summary>
        /// Refresh registry settings to comply with application settings.
        /// </summary>
        public static void Refresh()
        {
            Autostart = Settings.Default.Autostart;
        }
    }
}